package daoHibernate;

import java.io.Serializable;
import java.util.List;

import metier.Departement;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import dao.DAODepartement;

public class DAODepartementHBM extends DAOHibernate implements DAODepartement,
		Serializable {

	private static final long serialVersionUID = 1885687898541253564L;

	//Gestion du singleton
	private static DAODepartement oInstance = null;
	
	private	DAODepartementHBM() 
	{
	}

	public static DAODepartement getInstance()
	{
		if(oInstance == null)
			oInstance = new DAODepartementHBM();
		
		return oInstance;
	}	
	
	@Override
	public Departement get(int pIdDepartement)
	{
		Departement mDepartement = null;
		
		Session	mSession = null;
		
		try
		{
			mSession = connect();
			mDepartement = (Departement) mSession.get(Departement.class, pIdDepartement);
		}
		catch (Exception mException)
		{
			mException.printStackTrace();
		}
		finally
		{
			close(mSession);
		}
		return mDepartement;
	}
	
	@Override
	public Departement get(String login, String mdp)
	{
		Departement mDepartement = null;		
		Session	mSession = null;		
		Criteria mRequete=null;
		
		try
		{
			mSession = connect();
			mRequete = mSession.createCriteria(Departement.class);
			mRequete.add(Restrictions.eq("login",login));
			mRequete.add(Restrictions.eq("mdp",mdp));
			mDepartement = (Departement) mRequete.uniqueResult();
			
			if (mDepartement == null)
			{
				throw new Exception("le login ou le mot de passe fourni est incorrecte");
			}
			else
			{
				return mDepartement;
			}
		}
		catch (Exception mException)
		{
			mException.printStackTrace();
		}
		finally
		{
			close(mSession);
		}
		return null;
	}
	
	@Override
	public void save(Departement pDepartement) 
	{
		Session	mSession = null;
		
		try
		{
			mSession = connect();
			
			mSession.save(pDepartement);
		}
		catch(Exception mException)
		{
			mException.printStackTrace();
		}
		finally
		{
			close(mSession);
		}
	}
	
	@Override
	public List<Departement> loadAll()
	{
		Session	mSession = null;
		List<Departement> mListDepartement = null;
		Criteria mRequete = null;
		
		try
		{
			mSession = connect();
			mRequete = mSession.createCriteria(Departement.class);
			
			mListDepartement = mRequete.list();
			
		}
		catch(Exception mException)
		{
			mException.printStackTrace();
		}
		finally
		{
			close(mSession);
		}
		
		return mListDepartement;
	}
}